package com.social.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.social.pojo.*;
import com.social.service.SysMenuService;
import com.social.service.SysRoleMenuService;
import com.social.service.SysRoleService;
import com.social.dao.SysRoleDao;
import com.social.utils.StringUtil;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.social.constant.RedisConstants.SYSTEM_ROLE_TTL;
import static com.social.constant.RedisConstants.SYSYTEM_ROLE_KEY;

/**
* @author 25241
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2022-10-30 15:18:42
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole>
    implements SysRoleService{

    @Autowired
    private SysRoleDao sysRoleDao;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    SysRoleMenuService sysRoleMenuService;

    @Autowired
    SysMenuService sysMenuService;

    @Override
    public Result getAll(PageBean pageBean) {
        IPage<SysRole> page = sysRoleDao
                .selectPage(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), null);
        List<SysRole> roleList = page.getRecords();
        if (roleList == null) {
            return Result.fail(201, "权限信息获取失败");
        }
        for (SysRole role : roleList) {
            Wrapper<SysMenu> wrapper = new QueryWrapper<SysMenu>()
                    .inSql("id", "select menu_id from sys_role_menu where role_id = " + role.getId());
            List<SysMenu> menuList = sysMenuService.list(wrapper);
            role.setMenuList(menuList);
        }
        System.out.println("roleList" + roleList);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", roleList);
        resultMap.put("total", page.getTotal());
        return Result.ok(200, resultMap);
    }

    @Override
    public Result listAll() {
        Map<String,Object> resultMap=new HashMap<>();
        List<SysRole> roleList = list();
        System.out.println("roleList " + roleList);
        resultMap.put("roleList",roleList);
        return Result.ok(200, resultMap);
    }

    @Override
    public Result deleteById(Long[] ids) {
        boolean isRemove = removeByIds(Arrays.asList(ids));
        if (!isRemove) {
            return Result.fail(201, "删除权限失败");
        }
        for (Long id : ids) {
            String key = SYSYTEM_ROLE_KEY + id;
            stringRedisTemplate.delete(key);
        }

        return Result.ok(200);
    }

    @Override
    public Result add(SysRole sysRole) {

        if (sysRole.getId() == null || sysRole.getId() == -1){
            sysRole.setCreateTime(new Date());
            boolean isSave = save(sysRole);
            if (!isSave) {
                return Result.fail(201, "新增角色失败");
            }

            return Result.ok(200);
        } else{
            sysRole.setUpdateTime(new Date());
            boolean isUpdate = updateById(sysRole);
            if (!isUpdate){
                return Result.fail(201, "修改角色信息失败！");
            }

            String key = SYSYTEM_ROLE_KEY + sysRole.getId();
            String json = JSONUtil.toJsonStr(sysRole);
            stringRedisTemplate.opsForValue().set(key, json, SYSTEM_ROLE_TTL, TimeUnit.MINUTES);

            return Result.ok(200);
        }

    }

    @Override
    public Result update(SysRole sysRole) {

        boolean isSave = save(sysRole);

        if (!isSave){
            return Result.fail(201, "修改角色信息失败！");
        }

        String key = SYSYTEM_ROLE_KEY + sysRole.getId();
        String json = JSONUtil.toJsonStr(sysRole);
        stringRedisTemplate.opsForValue().set(key, json, SYSTEM_ROLE_TTL, TimeUnit.MINUTES);

        return Result.ok(200);
    }

    @Override
    public Result grantMenu(Long roleId, Long[] menuIds) {
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        Arrays.stream(menuIds).forEach(r ->{
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(r);
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenus.add(sysRoleMenu);
        });
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id",roleId));
        sysRoleMenuService.saveBatch(sysRoleMenus);
        return Result.ok(200);
    }


}




